<?php

class LoginController extends dmq\Controller
{
	protected $useDb = true;

	// Actions.
	const LOGOUT = 'Logout';

	public function doControll()
	{
		$this->title( 'Login' );

		// If trying to logout, do it.
		if ( $this->view->action() == self::LOGOUT )
		{
			$this->model->logout( $this->view->auth() );
			$this->view->message( 'You are now logged out.' );
		}
		
		// Tried to login.
		if ( $this->view->triedToLogin() )
		{
			require_once 'lib/Validation.php';
			$validate = new Validation();

			try
			{
				if ( !$validate->username( $this->view->getUsername() ) )
				{
					throw new Exception( 'Invalid username.' );
				}

				if ( !$validate->password( $this->view->getPassword() ) )
				{
					throw new Exception( 'Invalid password.' );
				}

				$this->model->login( $this->view->auth(), $this->view->getUsername(), $this->view->getPassword() );
				//skapar cookie som används till push-funktionen för när spelare joinat ett spel
				setcookie("userid", $this->view->auth()->user()->id());
				header( 'Location: index.php' );
			}
			catch ( Exception $e )
			{
				$this->view->error( $e->getMessage() );
			}
		}
		
		$this->view->buildLoginForm();
		
		$this->view->printErrors( '<p class="error"><span>Error :(</span> _ERROR_</p>' . "\r\n" );
		$this->view->printMessages( '<p class="message"><span>Success \o/</span> _MESSAGE_</p>' . "\r\n" );
	}
}
